//
//  XMPlayVideoView.m
//  XMKit
//
//  Created by Ce Liu on 2018/5/29.
//  Copyright © 2018年 ChenXiaoMing. All rights reserved.
//

#import "XMPlayVideoView.h"

// Lib
#import <AVFoundation/AVFoundation.h>

@interface XMPlayVideoView ()

@property (nonatomic, strong) AVPlayer *player;

@property (nonatomic, strong) AVPlayerItem *playerItem;

@property (nonatomic, strong) AVPlayerLayer *playerLayer;

@property (nonatomic, strong) AVAsset *asset;

@property (nonatomic, strong) NSTimer *checkTimer;

@property (nonatomic, assign) CGFloat duration;

@end

@implementation XMPlayVideoView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        
        NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"reloadVideo.mp4" ofType:nil];
        _asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:fullPath]];
        _playerItem = [AVPlayerItem playerItemWithAsset:_asset];
        _player = [[AVPlayer alloc]initWithPlayerItem:_playerItem];
        _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
        _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        
        [self.layer addSublayer:_playerLayer];

        [_player play];
        //监听PlayerItem
        [_playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        
        //添加进入按钮
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.frame = CGRectMake(kSCREENWIDTH - 115, kSCREENHEIGHT - 100, 80, 35);
        [btn setTitle:@"跳过" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor colorWithHexString:@"333333" alpha:0.6];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn addTarget:self action:@selector(btnclick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        
        self.checkTimer = [NSTimer scheduledTimerWithTimeInterval:7.0 target:self selector:@selector(playeraction) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:self.checkTimer forMode:NSRunLoopCommonModes];
    }
    return self;
}

- (void)show {
//    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    UIWindow *window = [self lastWindow];
    [window addSubview:self];
}

- (void)layoutSubviews {
    self.playerLayer.frame = self.bounds;
}

- (void)playeraction {
    self.playFinished();
    [self.playerLayer removeFromSuperlayer];
    self.playerLayer = nil;
    self.player = nil;
}

//监听获得消息
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    //判断链接状态
    if ([keyPath isEqualToString:@"status"]) {
        if (self.playerItem.status == AVPlayerItemStatusFailed) {
            NSLog(@"连接失败");
        }else if (self.playerItem.status == AVPlayerItemStatusUnknown){
            NSLog(@"未知的错误");
        }else{
            NSLog(@"准备播放");
            self.duration = CMTimeGetSeconds(self.playerItem.duration);
        }
    }
}

- (void)btnclick {
    [[NSNotificationCenter defaultCenter] postNotificationName:kPlayFinishedNotify object:nil];
    //btn点击事件 执行block
    self.playFinished();
    [self.playerLayer removeFromSuperlayer];
    self.playerLayer = nil;
    self.player = nil;
}

- (void)removeTimer {
    [self.checkTimer invalidate];
    self.checkTimer = nil;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.playerLayer removeFromSuperlayer];
    self.playerLayer = nil;
    self.player = nil;
    [self removeTimer];
}

@end
